<template>
  <page-wrap back dark hide-tab title="招聘名片" stayStill>
    <view class="recruitment">
      <view class="title">
        <view class="title-name">创建一览名片</view>
        <text class="title-label">仅需两步，开启高效招聘方式</text>
      </view>
      <u-form :model="form" ref="uForm" label-position="top">
        <u-form-item label="头像" prop="avatar">
          <view class="avatar" @click="handleAvatarClick">
            <view class="avatar-left">
              <text class="icon icon-tips"></text>
              <text>上传真实头像更容易得倒求职者的关注哦～</text>
            </view>
            <view class="avatar-img-wrap">
              <image class="avatar-img" :src="form.avatar || defaultAvatar" mode=""></image>
              <text class="icon icon-camera"></text>
            </view>
          </view>
        </u-form-item>
        <u-form-item label="姓名" prop="name">
          <u-input v-model="form.name" placeholder="请填入您的真实姓名" />
        </u-form-item>
        <u-form-item label="我的公司" prop="cname">
          <u-input
            v-model="form.cname"
            placeholder="请填写与营业执照完全一致的公司全称"
             clearable
            @input="handleInput"
            @confirm="handleSearch"
          />
        </u-form-item>
        <view v-show="form.cname"  class="kw-options">
          <view class="option" v-for="item in kwOptions" :key="item.name" @click="handleSearch(item)">{{item.name}}
          </view>
          <view v-show="loadEnd" class="end-tips"> 已经到底啦~ </view>
        </view>
        <u-form-item label="我的职位" prop="pnames">
          <u-input v-model="form.pnames" placeholder="请填写在当前公司任职职位" />
        </u-form-item>
        <u-form-item label="接收简历邮箱" prop="email">
          <u-input v-model="form.email" placeholder="请填写常用邮箱" />
        </u-form-item>
      </u-form>
    </view>
    <view class='next'>
      <button class="btn btn-primary" :class='{disable: disableNext}' @click="handleNext">
        下一步
      </button>
    </view>
    <u-action-sheet :list="actionlist" v-model="showActionSheet" @click="handleActionShellClick"></u-action-sheet>
    <u-popup v-model="showAvatarPopup" mode="bottom" safe-area-inset-bottom	>
      <view class="avatar-popup">
        <view class="default-img" @click="handleSetAvatar(default_man)">
          <image :src="default_man" mode="" />
          <text>默认头像1</text>
        </view>
        <view class="default-img" @click="handleSetAvatar(default_woman)">
          <image :src="default_woman" mode="" />
          <text>默认头像2</text>
        </view>
      </view>
      <view class="avatar-popup-action">
        <view class="btn btn-cancel" @click="showAvatarPopup = false">
          取消
        </view>
      </view>

    </u-popup>
    <u-icon name="more-dot-fill" size="52" class="btn-more" @click="showMore = true"></u-icon>
    <MoreAction :show.sync="showMore" :showGiveUp="false" />

  </page-wrap>
</template>

<script>
import { uploadAction, uploadBaseUrl } from "@/api/index";
import { getByteLength, checkEmailValid } from "@/utils/handle";
import {getCompanyNameByName} from "@/api/modules/company.js"
import MoreAction from "../components/moreAction.vue";
import personDetailMixin from "../mixins/personDetail.js";
import { debounce } from '@/utils/handle';
export default {
  mixins: [personDetailMixin],
  components: {
    MoreAction,
  },
  data() {
    var validateName = (rule, value, callback) => {
      if (getByteLength(value) < 4) return false
      return true
    };
    var validateEmail = (rule, value, callback) => {
      if (!checkEmailValid(value)) return false
      return true
    };
    return {
      defaultAvatar: this.$imgBase + "avatar-empty.jpg",
      default_man: "https://img3.job1001.com/newyp/images/default_man.png",
      default_woman: "https://img3.job1001.com/newyp/images/default_woman.png",
      companyList:[],
      kwOptions: [],
      actionlist: [{
        text: '默认头像',
      }, {
        text: '拍照'
      }, {
        text: '相册选择' 
      }],
      showDefaultAvatar: false,
      showActionSheet: false,
      showAvatarPopup: false,
      form: {
        avatar: '',
				name: '',
        cname: '',
				pnames: '',
				email: '',
      },
      rules: {
        name: [
          {
            required: true,
            validator: validateName,
						message: '至少输入2个汉字/4个字母', 
						trigger: ['blur'],
          },
        ],
        cname: [
          {
            required: true,
            validator: validateName,
						message: '至少输入2个汉字/4个字母', 
						trigger: ['blur'],
          },
        ],
        // pnames: [{ required: true, message: "请输入职位", trigger: "blur" }],
        // email: [
        //   { required: true, message: "请输入邮箱", trigger: "blur" },
        //   { validator: validateEmail, trigger: "blur", message: '请输入正确的邮箱地址' },
        // ],
      },
      showMore: false,
    }
  },
  computed: {
    disableNext() {
      if(!this.form.avatar || !this.form.name || !this.form.cname
      //  || !this.form.pnames || !this.form.email
       ) return true
      return false
    }
  },
  created() {
    uni.$on("uAvatarCropper", (path) => {
      uni.uploadFile({
        url: uploadAction,
        filePath: path,
        name: "file",
        success: (res) => {
          this.form.avatar = uploadBaseUrl + res.data
        },
      });
    });
    let info = uni.getStorageSync('recCardInfo')
    if(info) {
      Object.assign(this.form, info)
    }
    this.getPersonDetail().then(() => {
      let userInfo = getApp().globalData.userInfo;
      if(userInfo.pic) {
        this.form.avatar = userInfo.pic;
      } else {
        this.form.avatar = this.default_man;
      }
    })
    
  },
  beforeDestroyed(){
    uni.$off('uAvatarCropper')
  },

  methods: {
    toCropper() {
      uni.navigateTo({
        url: `/pagesSub/resume/cropper/index?destWidth=${600}&rectWidth=${300}`,
      })
    },
    handleAvatarClick() {
      this.showActionSheet = true
    },
    handleActionShellClick(index) {
      if(index == 0) {
        this.showAvatarPopup = true
      } else if(index == 1) {
        this.chooseImage('camera')
      } else if(index == 2) {
        // this.chooseImage('album')
        this.toCropper()
      }
    },
    handleSetAvatar(img) {
      this.form.avatar = img 
      this.showAvatarPopup = false
    },

    chooseImage(type) {
      uni.chooseImage({
        count: 1, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: [type], // album 从相册选图，camera 使用相机
        success: (res) => {
          var tempFilePaths = res.tempFilePaths[0]; //获取成功，读取文件路径
          uni.uploadFile({
            url: uploadAction,
            filePath: tempFilePaths,
            name: "file",
            success: (fileRes) => {
              if (fileRes.data) {
                let imgPath = "http://img106.job1001.com/" + fileRes.data;
                this.handleSetAvatar(imgPath)
              } else {
                this.form.avatar = ''
                uni.showToast({
                  icon: "none",
                  title: "头像上传失败",
                });
              }
            },
            fail: (err) => {
              this.form.avatar = ''
              uni.showToast({
                icon: "none",
                title: "头像上传失败",
              });
            },
          });
        }
      });
    },
    handleNext() {
      if(!this.form.avatar) {
        return uni.showToast({
          title: "请上传头像",
          icon: 'none'
        })
      }
			this.$refs.uForm.validate(valid => {
        if (valid) {
          uni.setStorageSync('recCardInfo', this.form)
          uni.navigateTo({
            url: '/pagesSub/company/companyList/index'
          });
        } else {
					console.log('验证失败');
          }
        });
    },
    handleInput: debounce(function() {
      this.reqGetCompanyNameByName();
      this.kwOptions = [];
    }, 500),
       // 根据企业名称获取企业
    reqGetCompanyNameByName() {
      if(!this.form.cname) return;
      if(this.form.cname.length < 2) return;
      const params = {
        companyName: this.form.cname,
      };
      this.loadEnd = false;
      getCompanyNameByName(params)
        .then((res) => {
          if (res.code == 200) {
          let list = res.data || [];
          this.kwOptions = list;
          }
        })
        .finally(() => {
        this.loadEnd = true;
      });
    },
    handleSearch(item) {
      if (!item.name) return;
      this.form.cname = item.name;
      this.kwOptions=[];
    },
 
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
	}
}
</script>

<style lang="scss" scoped>
.recruitment {
  flex: 1;
  padding: $uni-spacing-col-big;
  padding-bottom: calc(160rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(160rpx + env(safe-area-inset-bottom));
  background-color: $uni-bg-color;

  .title {
    margin-bottom: $uni-spacing-col-big;
    &-name {
      font-size: 48rpx;
      font-weight: bold;
      color: #000000;
      margin-bottom: $uni-spacing-col-lg;
    }
    &-label {
      font-size: $uni-font-size-base;
      color: $uni-text-color-666;
    }
  }

  .avatar {
    display: flex;
    justify-content: space-between;
    margin-top: -40rpx;
    width: 100%;
    &-left {
      align-self: flex-end;
      font-size: $uni-font-size-sm;
      color: $u-type-warning;
      .icon-tips {
        width: 22rpx;
        height: 22rpx;
        margin-right: 8rpx;
        margin-bottom: 4rpx;
        background-image: url($img-base + 'company/tips.png?v=1');
      }
    }
    &-img {
      &-wrap {
        width: 100rpx;
        height: 100rpx;
      }
      width: 100%;
      height: 100%;
      border-radius: $uni-border-radius-circle;
    }
  }
  
}
.next {
  position: fixed;
  bottom: 0;
  z-index: 10;
  background-color: $uni-bg-color;
  width: 100%;
  padding: 32rpx;
  padding-bottom: calc(32rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(32rpx + env(safe-area-inset-bottom));
  .btn {
    font-size: $uni-font-size-lg;
  }
  .btn.disable {
    opacity: 0.5;
  }
}
.avatar-popup {
  padding: $uni-spacing-col-big;
  padding-top: 80rpx;
  display: flex;
  justify-content: space-around;
  .default-img {
    image {
      margin: 0 auto;
      width: 100rpx;
      height: 100rpx;
      border-radius: 50%;
    }
  }
  &-action {
    margin: 40rpx 0 40rpx 0;
    padding: 0 32px;
    .btn {
      width: 100%;
      &-cancel {
        line-height: 60rpx;
        padding: 0 40rpx;
        border: 1px solid #EEE;
      }
    }
  }

}
.kw-options {
  width: 100%;
  z-index: 1;
  background-color: #ffffff;
  overflow-y: scroll;
  .option {
    margin: 0 32rpx;
    padding: 36rpx 0;
    border-bottom: 2rpx solid #F1F1F1;

    &:last-child {
      border: none;
    }

    .high-light {
      color: #FF7731;
    }
  }

  .end-tips {
    padding: 32rpx 0;
    font-size: $uni-font-size-nor;
    color: #BFBFBF;
    text-align: center;
  }
}

.btn-more {
  position: absolute;
  right: 30rpx;
  top: 20rpx;
}
</style>